/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Presentacion;

import ModeloLogicoSistema.AdministradorCliente;
import ModeloLogicoSistema.Cliente;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.ListIterator;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author debo
 */
public class BuscarCliente extends javax.swing.JDialog {
    private ArrayList<Cliente> clientes=null;
    private AdministradorCliente admCliente;
    private String encabezadosTabla[] ={"ID","Nombre","Apellido","Telefono","Celular","Dirección","Localidad"};
    private boolean aceptado=true;
    
    Cliente cliente=null;
    
    /**
     * Creates new form BuscarCliente
     */
   private void cargarTodosLosClientes() throws SQLException{
       this.clientes=null;
       this.clientes=(ArrayList)admCliente.cargarTodosLosClientes();
   }
   
   
   /*Esta funcion es un ASCO debe morir, DEBE MORIR*/
   boolean fueAceptado(){
       return aceptado;
   }

   void habilitarModificacion(){
       this.jButton2.setVisible(true);
       this.jBtnCancelar.setVisible(true);
       this.jBtnEliminar.setVisible(false);
       this.jButton1.setVisible(false);
       this.BtnResetear.setVisible(false);
   }
   
   void habilitarEliminar(){
       this.jBtnEliminar.setVisible(true);
       this.BtnResetear.setVisible(true);
       this.jButton1.setVisible(false);
       this.jBtnCancelar.setVisible(true);
       this.jButton2.setVisible(false);
   }
   
   
   void habilitarBusqueda(){
       this.jBtnEliminar.setVisible(false);
       this.BtnResetear.setVisible(true);
       this.jButton1.setVisible(true);
       this.jBtnCancelar.setVisible(true);
       this.jButton2.setVisible(false);
   }
   
   private void cargarDatosEnTabla(){
       DefaultTableModel modelo=(DefaultTableModel) tablaCliente.getModel();
        try {
            cargarTodosLosClientes();
        } catch (SQLException ex) {
            Logger.getLogger(BuscarCliente.class.getName()).log(Level.SEVERE, null, ex);
        }
       ListIterator it=this.clientes.listIterator(0);
       while(it.hasNext()){
            Cliente c = (Cliente)it.next();
            String dir=c.getCalle()+" "+c.getNroCalle();
            String direccion;
            if(c.getPisoNro().length()!=0 & c.getPisoNro()!=null){
                direccion=dir+", "+c.getPisoNro();
            }
            else direccion=dir;
            String domicilio=direccion+c.getPisoNro();
            Object [] fila={c.getNroCliente(),c.getNombre(),c.getApellido(),
            c.getTelFijo(),c.getCel(),direccion,c.getLocalidad()};
            modelo.addRow(fila);
      }
   }
   
   private void actualizarTablaCliente() throws SQLException{
       DefaultTableModel modeloTabla= new DefaultTableModel();
       modeloTabla.setColumnIdentifiers(encabezadosTabla);
       tablaCliente.setModel(modeloTabla);
       cargarDatosEnTabla();
   }
   
   
   private void actualizarTablaBusquedaCliente() throws SQLException{
       
       DefaultTableModel modeloTabla= (DefaultTableModel)this.tablaCliente.getModel();
       int canFilas=modeloTabla.getRowCount();
       int fila=0;
       for(int i=0;i<canFilas;i++)
            modeloTabla.removeRow(fila);
       cargarDatosBusqueda();
   }
   
   private void cargarDatosBusqueda(){
       DefaultTableModel modelo= (DefaultTableModel)this.tablaCliente.getModel();
       ListIterator it=this.clientes.listIterator(0);
       while(it.hasNext()){
            Cliente c = (Cliente)it.next();
            String dir=c.getCalle()+" "+c.getNroCalle();
            String direccion;
            if(c.getPisoNro().length()!=0 & c.getPisoNro()!=null){
                direccion=dir+", "+c.getPisoNro();
            }
            else direccion=dir;
            String domicilio=direccion+c.getPisoNro();
            Object [] fila={c.getNroCliente(),c.getNombre(),c.getApellido(),
            c.getTelFijo(),c.getCel(),direccion,c.getLocalidad()};
            modelo.addRow(fila);
      }
   }
   
   /**
    * Considero que cada elemento de la tabla ocupa la misma posición que en la
    * lista.
    */
   Cliente getClienteSeleccionado(){
       int posicion=this.tablaCliente.getSelectedRow();
       if(posicion!=-1) {           
           this.cliente= this.clientes.remove(posicion);
           return this.cliente;
       }
       return null;
   }
   
    public BuscarCliente(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
        this.aceptado=false;
        this.clientes=new ArrayList<>();
        this.setLocationRelativeTo(null);
        this.setTitle("      Buscar Cliente ");
        DefaultTableModel modeloTabla= new DefaultTableModel();
        modeloTabla.setColumnIdentifiers(encabezadosTabla);
        tablaCliente.setModel(modeloTabla);
        
        try {
            this.admCliente = new AdministradorCliente();
            this.clientes=(ArrayList)admCliente.cargarTodosLosClientes();
            cargarDatosEnTabla();
        } catch (SQLException ex) {
            Logger.getLogger(BuscarCliente.class.getName()).log(Level.SEVERE, null, ex);
        }
    }


    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jBtnModificar = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        tablaCliente = new javax.swing.JTable();
        jBtnCancelar = new javax.swing.JButton();
        BtnResetear = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();
        jCBBusqueda = new javax.swing.JComboBox();
        jBtnEliminar = new javax.swing.JButton();
        jTextField1 = new javax.swing.JTextField();
        jButton1 = new javax.swing.JButton();
        jButton1.setVisible(false);
        jButton2 = new javax.swing.JButton();

        jBtnModificar.setText("Modificar");
        jBtnModificar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jBtnModificarActionPerformed(evt);
            }
        });

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        tablaCliente.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jScrollPane1.setViewportView(tablaCliente);

        jBtnCancelar.setText("Cancelar");
        jBtnCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jBtnCancelarActionPerformed(evt);
            }
        });

        BtnResetear.setText("Resetear");
        BtnResetear.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                BtnResetearActionPerformed(evt);
            }
        });

        jButton3.setText("Buscar");
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });

        jCBBusqueda.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "IdCliente", "Nombre", "Apellido", "Telefono", "Celular", "" }));
        jCBBusqueda.setSelectedItem("idCliente");
        jCBBusqueda.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jCBBusquedaActionPerformed(evt);
            }
        });

        jBtnEliminar.setText("Eliminar");
        jBtnEliminar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jBtnEliminarActionPerformed(evt);
            }
        });

        jButton1.setText("Aceptar");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButton2.setText("Modificar");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(jBtnEliminar, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(22, 22, 22)
                        .addComponent(BtnResetear, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(jBtnCancelar, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 572, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 85, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jCBBusqueda, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(jButton3)
                        .addGap(0, 0, Short.MAX_VALUE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(14, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton3)
                    .addComponent(jCBBusqueda, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 205, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jBtnCancelar)
                    .addComponent(BtnResetear)
                    .addComponent(jBtnEliminar)
                    .addComponent(jButton1)
                    .addComponent(jButton2))
                .addContainerGap())
        );

        jButton1.getAccessibleContext().setAccessibleName("BtnAceptar");

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jBtnCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBtnCancelarActionPerformed

        this.dispose();
    }//GEN-LAST:event_jBtnCancelarActionPerformed

    private void BtnResetearActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BtnResetearActionPerformed
        try {
            this.cargarTodosLosClientes();
            this.actualizarTablaBusquedaCliente();
            
        } catch (SQLException ex) {
            Logger.getLogger(BuscarCliente.class.getName()).log(Level.SEVERE, null, ex);
        }
        
    }//GEN-LAST:event_BtnResetearActionPerformed

    private void jCBBusquedaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jCBBusquedaActionPerformed
        
    }//GEN-LAST:event_jCBBusquedaActionPerformed

    private void jBtnModificarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBtnModificarActionPerformed
        this.cliente=this.getClienteSeleccionado();
        try {
            if(this.cliente==null){
            
            }
            else{
                ModificacionCliente modCliente=new ModificacionCliente
                    (null, rootPaneCheckingEnabled,cliente);
                modCliente.setVisible(true);
                this.actualizarTablaCliente();
            }
            
        } catch (SQLException ex) {
            Logger.getLogger(BuscarCliente.class.getName()).log(Level.SEVERE, null, ex);
        }
      

    }//GEN-LAST:event_jBtnModificarActionPerformed

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
        String eleccionBusqueda =jCBBusqueda.getSelectedItem().toString();
      
        this.clientes=new ArrayList<> ();
        if(eleccionBusqueda.equalsIgnoreCase("IdCliente") ){
            if(!jTextField1.getText().isEmpty())
                try {
                    Integer valorBusqueda=new Integer (jTextField1.getText());
                    clientes.add( this.admCliente.cargarCliente(valorBusqueda));
                //this.cargarTabla();
                    this.actualizarTablaBusquedaCliente();
                } catch (SQLException ex) {
                    Logger.getLogger(BuscarCliente.class.getName()).log(Level.SEVERE, null, ex);
            }
            else{
                try {
                    this.cargarTodosLosClientes();
                    this.actualizarTablaBusquedaCliente();
                } catch (SQLException ex) {
                    Logger.getLogger(BuscarCliente.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
        if(eleccionBusqueda.equalsIgnoreCase("Nombre") ){
            
            if(! jTextField1.getText().isEmpty()){
                String valorBusqueda=jTextField1.getText();
                clientes=(ArrayList<Cliente>) this.admCliente.buscarClientePorNombre(valorBusqueda);
                try {
                //this.cargarTabla();
                    this.actualizarTablaBusquedaCliente();
                //this.cargarDatosEnTabla();
                } catch (SQLException ex) {
                    Logger.getLogger(BuscarCliente.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            else{
                try {
                    this.cargarTodosLosClientes();
                    this.actualizarTablaBusquedaCliente();
                } catch (SQLException ex) {
                    Logger.getLogger(BuscarCliente.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
        if(eleccionBusqueda.equalsIgnoreCase("Apellido")){
            if(! jTextField1.getText().isEmpty()){
                String valorBusqueda=jTextField1.getText();
                clientes=(ArrayList<Cliente>) this.admCliente.buscarClientePorApellido(valorBusqueda);
                try {
                    this.actualizarTablaBusquedaCliente();
                } catch (SQLException ex) {
                    Logger.getLogger(BuscarCliente.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            else{
                try {
                    this.cargarTodosLosClientes();
                    this.actualizarTablaBusquedaCliente();
                } catch (SQLException ex) {
                    Logger.getLogger(BuscarCliente.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
        if(eleccionBusqueda.equalsIgnoreCase("Telefono")){
            if(! jTextField1.getText().isEmpty()){
                String valorBusqueda=jTextField1.getText();
                clientes=(ArrayList<Cliente>) this.admCliente.buscarClientePorTel(valorBusqueda);
                try {
                    this.actualizarTablaBusquedaCliente();
                } catch (SQLException ex) {
                    Logger.getLogger(BuscarCliente.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            else{
                try {
                    this.cargarTodosLosClientes();
                    this.actualizarTablaBusquedaCliente();
                } catch (SQLException ex) {
                    Logger.getLogger(BuscarCliente.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
            
        if(eleccionBusqueda.equalsIgnoreCase("Celular")){
            if(! jTextField1.getText().isEmpty()){
                String valorBusqueda=jTextField1.getText();
                clientes=(ArrayList<Cliente>) this.admCliente.buscarClientePorCel(valorBusqueda);
                try {
                    this.actualizarTablaBusquedaCliente();
                } catch (SQLException ex) {
                    Logger.getLogger(BuscarCliente.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            else{
                try {
                    this.cargarTodosLosClientes();
                    this.actualizarTablaBusquedaCliente();
                } catch (SQLException ex) {
                    Logger.getLogger(BuscarCliente.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            
        }
         /*
        if(eleccionBusqueda.equalsIgnoreCase("Direccion")){
            String valorBusqueda=jTextField1.getText();
            String Nro=valorBusqueda.s;
            clientes=(ArrayList<Cliente>) this.admCliente.buscarClientePorDomicilio(valorBusqueda, WIDTH);
            this.cargarTabla();
        }*/
    }//GEN-LAST:event_jButton3ActionPerformed

    private void jBtnEliminarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBtnEliminarActionPerformed
        try {
            int opcion=JOptionPane.showConfirmDialog(null, "Esta segudo que desea eliminar este cliente", "Eliminar cliente", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE);
            if(opcion==JOptionPane.YES_OPTION){
                this.cliente=this.getClienteSeleccionado();
                this.admCliente.eliminarCliente(cliente.getNroCliente());
                this.actualizarTablaCliente();
            }else{
                return;
            }
            
        } catch (SQLException ex) {
            Logger.getLogger(BuscarCliente.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_jBtnEliminarActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        this.aceptado=true;
        this.setVisible(false);
    }//GEN-LAST:event_jButton1ActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        this.cliente=this.getClienteSeleccionado();
        try {
            if(this.cliente==null){
            
            }
            else{
                ModificacionCliente modCliente=new ModificacionCliente
                    (null, rootPaneCheckingEnabled,cliente);
                modCliente.setVisible(true);
                this.actualizarTablaCliente();
            }
            
        } catch (SQLException ex) {
            Logger.getLogger(BuscarCliente.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_jButton2ActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(BuscarCliente.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(BuscarCliente.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(BuscarCliente.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(BuscarCliente.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the dialog */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                BuscarCliente dialog = new BuscarCliente(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                    @Override
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton BtnResetear;
    private javax.swing.JButton jBtnCancelar;
    private javax.swing.JButton jBtnEliminar;
    private javax.swing.JButton jBtnModificar;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JComboBox jCBBusqueda;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextField jTextField1;
    private javax.swing.JTable tablaCliente;
    // End of variables declaration//GEN-END:variables

}
